package com.cssy.yd.logic.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.basic.service.IBasicStorageService;
import com.cssy.yd.logic.entity.LogicPoReturnItemBatchDO;
import com.cssy.yd.logic.entity.LogicPoReturnItemDO;
import com.cssy.yd.logic.entity.LogicPoWareItemBatchDO;
import com.cssy.yd.logic.entity.LogicSoDO;
import com.cssy.yd.logic.entity.LogicSoQuoteProductDO;
import com.cssy.yd.logic.entity.LogicSoReturnDO;
import com.cssy.yd.logic.entity.LogicSoReturnItemBatchDO;
import com.cssy.yd.logic.entity.LogicSoReturnItemDO;
import com.cssy.yd.logic.entity.LogicSoWareDO;
import com.cssy.yd.logic.entity.LogicSoWareItemBatchDO;
import com.cssy.yd.logic.entity.LogicSoWareItemDO;
import com.cssy.yd.logic.entity.LogicSoWareItemFreezedealbatchDO;
import com.cssy.yd.logic.service.ILogicSoReturnService;
import com.cssy.yd.logic.service.ILogicSoService;
import com.cssy.yd.logic.service.ILogicSoWareItemService;
import com.cssy.yd.logic.service.ILogicSoWareService;
import com.cssy.yd.logic.util.SqlUtil;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.OutJsonGrid;
import com.yuendong.sy.service.code.impl.SyCodeService;

/**
 * 销售退货控制器
 * @author huang.xuming [2013-8-23]
 *
 */
@Controller
@RequestMapping("/yd/logic/soreturn")
public class SoReturnController extends BaseController<LogicSoReturnDO> {
	private static final Logger logger = Logger.getLogger(SoReturnController.class);
	
	private static final String MANAGER = "/yd/logic/soreturn/SoReturnManager";// 列表页面
	private static final String EIDT = "/yd/logic/soreturn/SoReturnOperation";// 添加、修改、显示页面
	private static final String ITEMMANAGER = "/yd/logic/soreturn/SoReturnItemManager";// 添加、修改、显示页面

	@Resource(name = "logicSoService")
	private ILogicSoService logicSoService;
	
	@Resource(name = "logicSoReturnService")
	private ILogicSoReturnService logicSoReturnService;

	@Resource(name = "logicSoWareService")
	private ILogicSoWareService logicSoWareService;
	
	@Resource(name = "logicSoWareItemService")
	private ILogicSoWareItemService logicSoWareItemService;

	@Resource(name = "basicwhService")
	private IBasicStorageService basicwhService;

	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;

	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;

	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}
	@RequestMapping(value="itemManager")
	public String itemManager(HttpServletRequest request, Model model)
			throws Exception {
		String itemdata =request.getParameter("data");
		String billstatus =request.getParameter("billstatus");
		String updstatus =request.getParameter("updstatus");
		LogicSoReturnItemDO returnItemDO=JSONArray.parseObject(new String(itemdata.getBytes("ISO-8859-1"),"UTF-8"), LogicSoReturnItemDO.class);
		if(returnItemDO.getItemBatch() != null & !"".equals(returnItemDO.getItemBatch())){
			request.setAttribute("itemBatch", returnItemDO.getItemBatch());
		}
		request.setAttribute("type", returnItemDO.getSourceBillType());
		request.setAttribute("updstatus", updstatus);
		request.setAttribute("billstatus", billstatus);
		return ITEMMANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		Map<String,Object> sqlMap = SqlUtil.sqlUtil.roleWhSqlFilter(request, scUserRolePlaceService,"whcode");
		scs.addCondition((String)sqlMap.get("option"), (List<?>)sqlMap.get("roleWhList"));
		SearchResult result = logicSoReturnService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);

	}
	@RequestMapping(value = "/itemlist")
	public void itemlist(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String itembatch =request.getParameter("itembatch");
		String updstatus = request.getParameter("updstatus");
		String type = request.getParameter("type");
		SearchResult result= new SearchResult();
		List<LogicSoReturnItemBatchDO> batchDOs = new ArrayList<LogicSoReturnItemBatchDO>();
		if("1".equals(updstatus)){
			if(itembatch != null  && !"".equals(itembatch)){
				batchDOs=JSONArray.parseArray(new String(itembatch.getBytes("ISO-8859-1"),"UTF-8"), LogicSoReturnItemBatchDO.class);
			}
		}else{
			if(itembatch != null  && !"".equals(itembatch)){
				if("1".equals(type)){
					 List<LogicSoWareItemBatchDO> itemBatchDOs=JSONArray.parseArray(new String(itembatch.getBytes("ISO-8859-1"),"UTF-8"), LogicSoWareItemBatchDO.class);
					LogicSoReturnItemBatchDO returnItemBatchDO = null;
						if(itemBatchDOs != null && itemBatchDOs.size() > 0){
							for (LogicSoWareItemBatchDO soWareItemBatchDO : itemBatchDOs) {
								if((soWareItemBatchDO.getYtBQuantity()==null?0.0:soWareItemBatchDO.getYtBQuantity()) < (soWareItemBatchDO.getProdBSfquantity()==null?0.0:soWareItemBatchDO.getProdBSfquantity())){
									returnItemBatchDO = new LogicSoReturnItemBatchDO();
									returnItemBatchDO.setProdNo(soWareItemBatchDO.getProdNo());
									returnItemBatchDO.setProdName(soWareItemBatchDO.getProdName());
									returnItemBatchDO.setProdSpecDesc(soWareItemBatchDO.getProdSpecDesc());
									returnItemBatchDO.setProdModel(soWareItemBatchDO.getProdModel());
									returnItemBatchDO.setProdBatch(soWareItemBatchDO.getProdBatch());
									returnItemBatchDO.setStatus(soWareItemBatchDO.getStatus());
									returnItemBatchDO.setProdBUnit(soWareItemBatchDO.getProdBUnit());
									returnItemBatchDO.setProdUnitConvert(soWareItemBatchDO.getProdUnitConvert());
									returnItemBatchDO.setProdUnit(soWareItemBatchDO.getProdUnit());
									returnItemBatchDO.setProdSfquantity(soWareItemBatchDO.getProdSfquantity());
									returnItemBatchDO.setProdBSfquantity(soWareItemBatchDO.getProdBSfquantity());
									returnItemBatchDO.setYtQuantity(soWareItemBatchDO.getYtQuantity());
									returnItemBatchDO.setYtBQuantity(soWareItemBatchDO.getYtBQuantity());
									batchDOs.add(returnItemBatchDO);
								}
							}
						}
					}else if("2".equals(type)){
						List<LogicSoWareItemFreezedealbatchDO> itemBatchDOs=JSONArray.parseArray(new String(itembatch.getBytes("ISO-8859-1"),"UTF-8"), LogicSoWareItemFreezedealbatchDO.class);
						LogicSoReturnItemBatchDO returnItemBatchDO = null;
							if(itemBatchDOs != null && itemBatchDOs.size() > 0){
								for (LogicSoWareItemFreezedealbatchDO sFreezedealbatchDO : itemBatchDOs) {
									if((sFreezedealbatchDO.getYtBQuantity()==null?0.0:sFreezedealbatchDO.getYtBQuantity()) < (sFreezedealbatchDO.getProdBSfquantity()==null?0.0:sFreezedealbatchDO.getProdBSfquantity())){
										returnItemBatchDO = new LogicSoReturnItemBatchDO();
										returnItemBatchDO.setProdNo(sFreezedealbatchDO.getProdNo());
										returnItemBatchDO.setProdName(sFreezedealbatchDO.getProdName());
										returnItemBatchDO.setProdSpecDesc(sFreezedealbatchDO.getProdSpecDesc());
										returnItemBatchDO.setProdModel(sFreezedealbatchDO.getProdModel());
										returnItemBatchDO.setProdBatch(sFreezedealbatchDO.getProdBatch());
										returnItemBatchDO.setStatus(sFreezedealbatchDO.getStatus());
										returnItemBatchDO.setProdBUnit(sFreezedealbatchDO.getProdBUnit());
										returnItemBatchDO.setProdUnitConvert(sFreezedealbatchDO.getProdUnitConvert());
										returnItemBatchDO.setProdUnit(sFreezedealbatchDO.getProdUnit());
										returnItemBatchDO.setProdSfquantity(sFreezedealbatchDO.getProdSfquantity());
										returnItemBatchDO.setProdBSfquantity(sFreezedealbatchDO.getProdBSfquantity());
										returnItemBatchDO.setYtQuantity(sFreezedealbatchDO.getYtQuantity());
										returnItemBatchDO.setYtBQuantity(sFreezedealbatchDO.getYtBQuantity());
										batchDOs.add(returnItemBatchDO);
									}
								}
							}
					}
				}
			}
			result.setRecordCount(batchDOs.size());
			result.setResults(batchDOs);
	
			 OutJsonGrid out=new OutJsonGrid(result);
			 out.printJSon(response);
		}

	@RequestMapping(value = "/sowareitemlist")
	public void sowareitemlist(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("sowareid");
		SearchResult result = new SearchResult();
		if (StringUtils.isNotBlank(id)) {
			//bean转换
			SearchConditions scs = new SearchConditions();
			scs.addCondition("sowareid",id,SearchCondition.OP_EQUAL);
			scs.setRemovedProperty(null);
			List<LogicSoWareItemDO> pw = logicSoWareItemService.findItemListBysowareId(id);
//			List<LogicSoReturnItemDO> itemlist=new ArrayList<LogicSoReturnItemDO>();
//			List<LogicSoWareItemDO> pwCollectLs = new ArrayList<LogicSoWareItemDO>();
			if(null != pw && pw.size()>0){
				for(int i=0;i<pw.size();i++){
					pw.get(i).setRemark(null);
					pw.get(i).setId(null);
					pw.get(i).setVal(null);
//					LogicSoReturnItemDO pr=new LogicSoReturnItemDO();
//					pr.setMaterialsid(pwitem.getMaterialsid());
//					pr.setProdModel(pwitem.getProdModel());
//					pr.setProdSpecDesc(pwitem.getProdSpecDesc());
//					pr.setProdNo(pwitem.getProdNo());
//					pr.setProdName(pwitem.getProdName());
//					pr.setProdBatch(pwitem.getProdBatch());
//					pr.setProdPrice(pwitem.getProdPrice());
//					pr.setProdBUnit(pwitem.getProdBUnit());
//					pr.setProdUnit(pwitem.getProdUnit());
//					pr.setStatus(pwitem.getStatus());
//					pr.setProdUnitConvert(pwitem.getProdUnitConvert());
//					pr.setProdBQuantity(pwitem.getProdBQuantity());
//					pr.setProdQuantity(pwitem.getProdQuantity());
//					pr.setProdBSfquantity(pwitem.getProdBSfquantity());
//					pr.setProdSfquantity(pwitem.getProdSfquantity());
//					pr.setYtBQuantity(pwitem.getYtBQuantity());
//					pr.setYtQuantity(pwitem.getYtQuantity());
//					
//					itemlist.add(pr);
					pw.get(i).setUpdstatus("0");
				}
				
				//重复的产品进行汇总
//				Map<String,LogicSoWareItemDO> pwCollectMap = new HashMap<String,LogicSoWareItemDO>();
//				for(LogicSoWareItemDO pwitem : pw){
//					LogicSoWareItemDO pwitem2 = pwCollectMap.get(pwitem.getProdNo()+pwitem.getStatus()+pwitem.getProdBatch());
//					if(null==pwitem2){
//						pwCollectMap.put(pwitem.getProdNo()+pwitem.getStatus()+pwitem.getProdBatch(),pwitem);
//					}else{
//						//---汇总
//						//实发
//						pwitem2.setProdSfquantity(pwitem2.getProdSfquantity()+pwitem.getProdSfquantity());
//						pwitem2.setProdBSfquantity(pwitem2.getProdBSfquantity()+pwitem.getProdBSfquantity());
//						//应退
//						pwitem2.setYtQuantity(pwitem2.getYtQuantity()+pwitem.getYtQuantity());
//						pwitem2.setYtBQuantity(pwitem2.getYtBQuantity()+pwitem.getYtBQuantity());
//						
//					}
//				}
//				
//				pwCollectLs.addAll(pwCollectMap.values());
			}
			
			result.setResults(pw);
			result.setRecordCount(pw.size());
		}
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}


	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		
		if (OperationFlag.ADD.equals(flag)) {
			// 新增加时操作
			model.addAttribute("flag", "ADD");
		} else {
			LogicSoReturnDO lrd = logicSoReturnService.findListById(id);
			/*SearchConditions scs2 = new SearchConditions();
			scs2.addCondition("returnsoid", lrd.getId(), SearchCondition.OP_EQUAL);
			scs2.setRemovedProperty(null);
			scs2.setLimitPage(false);
			scs2.setOrderBy("prod_no");
			@SuppressWarnings("unchecked")
			List<LogicPoReturnItemDO> lpitem = logicSoReturnService.findItemListByExample(scs2).getResults();*/
			model.addAttribute("soreturn", lrd);
			//model.addAttribute("returnitem", lpitem);
			model.addAttribute("flag", "EDIT");
		}
		
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		model.addAttribute("solist", findsoListCanReturn());
		return EIDT;
	}
	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicSoReturnDO lrd = logicSoReturnService.findListById(id);
			SearchConditions scs2 = new SearchConditions();
			scs2.addCondition("returnsoid", lrd.getId(), SearchCondition.OP_EQUAL);
			scs2.setRemovedProperty(null);
			scs2.setLimitPage(false);
			scs2.setOrderBy("prod_no");
			List<LogicPoReturnItemDO> lpitem = logicSoReturnService.findItemListByExample(scs2).getResults();
			OutJsonGrid out = new OutJsonGrid(lpitem);
			out.printJSon(response);
		}
	}


	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicSoReturnDO curAP, BindingResult result, Model model)
			throws SyBaseException {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String itemdata = request.getParameter("itemdata");
		if (StringUtils.isBlank(itemdata)) {
			bodyMap.isFail();
			bodyMap.configWebInfor("物料不能为空！");
			return bodyMap.modelMap;
		}
		try {
			logicSoReturnService.returnsave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;

	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields = ids.split(",");
			for (String field : fields) {
				LogicSoReturnDO ld = logicSoReturnService.findListById(field);
				ld.setRemoved(1);
				logicSoReturnService.update(ld, SessionUtil.getUser(request));
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}

	
	/**
	 * 根据订单ID获取可退货的入库单号
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getsowarelistCanReturnBySoNo")
	public void getsowarelistCanReturnBySoNo(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		
		try{
			String soNo = request.getParameter("soNo");
			List<LogicSoWareDO> list = findsowarelistCanReturnBySoNo(soNo);
			
			response.setContentType("text/text;charset=UTF-8");
			PrintWriter out=null;
			Map<String ,Object> map = new HashMap<String, Object>();
			map.put("list", list);
			 try {
				 out=response.getWriter();
				 out.write(JSONObject.toJSONString(map));
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
			}finally{
				if(out!=null){
					out.flush();
					out.close();
				}
			}
		}catch(Exception e){
			logger.warn(e.getMessage(), e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		
	}
	
	/**
	 * 根据订单ID获取可退货的入库单号
	 * @param soNo
	 * @return
	 */
	private List<LogicSoWareDO> findsowarelistCanReturnBySoNo(String soNo){
		SearchConditions scs = new SearchConditions();
		scs.addCondition("billstatus","2",SearchCondition.OP_EQUAL);//审批完结
		scs.addCondition("ware_status","4",SearchCondition.OP_NOTEQUAL);//未全部退货
		if(StringUtils.isNotBlank(soNo)){
			scs.addCondition("so_no",soNo,SearchCondition.OP_EQUAL);//审批完结
		}
		scs.setLimitPage(false);
		SearchResult result= logicSoWareService.findListByExample(scs);
		
		@SuppressWarnings("unchecked")
		List<LogicSoWareDO> ls = result.getResults();
		return ls;
	}
	
	/**
	 * 获取可退货的订单号
	 * @return
	 */
	private List<LogicSoDO> findsoListCanReturn(){
		SearchConditions scs = new SearchConditions();
		scs.addCondition("billstatus","4,5",SearchCondition.OP_IN);//审批完结
		scs.addCondition("ware_status","1,2,3",SearchCondition.OP_IN);//部分出库、全部出库
		SearchResult result= logicSoService.findListByExample(scs);
		
		@SuppressWarnings("unchecked")
		List<LogicSoDO> ls = result.getResults();
		return ls;
	}
}
